﻿using System.ComponentModel.Composition;
using System.ComponentModel.DataAnnotations;

namespace OperationPlugins.Validators.DataAnnotations
{
    [Export(typeof(IUsePluginValidatorsAttributeResolveOperation))]
    [DefaultPriority]
    internal sealed class DefaultIUsePluginValidatorsAttributeResolveOperation : IUsePluginValidatorsAttributeResolveOperation
    {
        /// <summary>
        /// Resolves the current operation.
        /// </summary>
        /// <remarks>
        /// The default value is <see cref="Operations.Any"/>.
        /// </remarks>
        /// <param name="value">The value to validate.</param>
        /// <param name="validationContext">Describes the context in which a data annotations validation check is performed.</param>
        /// <returns>The current operation.</returns>
        OperationId IUsePluginValidatorsAttributeResolveOperation.ResolveOperation(object value, ValidationContext validationContext)
        {
            OperationId operation = OperationPluginsContext.Current.CurrentActionOperation;

            if (operation == null)
            {
                var e = new ResolveOperationEventArgs(value, validationContext);

                DataAnnotationsValidationResourceResolver.OnResolveOperation(this, e);

                operation = e.Resolved;
            }

            return operation ?? (Operations.Any);
        }
    }
}
